<template>
	<view class="container">
		<!-- 收货地址 -->
		<view class="address cu-list menu-avatar radius-bock" style="margin-bottom: 20rpx;">
			<view class="cu-item">
				<view class="cu-avatar round wanl-bg-orange"><text class="wlIcon-weizhi1"></text></view>
				<view class="content" v-if="addressData.address" @tap="userAddress()" style="left: 130rpx;!important">
					<view>
						<text class="wanl-pip margin-right-sm">{{ addressData.name }}</text>
						<text class="wanl-gray-light text-sm">{{ addressData.mobile }}</text>
					</view>
					<view class="text-sm wanl-pip text-cut">{{ addressData.province}} {{ addressData.city }}
						{{ addressData.district }} {{ addressData.address }}
					</view>
				</view>
				<view class="content" @tap="addAddress('newadd')" v-else>
					<view class="text-sm wanl-pip text-cut">点击此处填写收货地址</view>
				</view>
				<view class="action"><text class="wlIcon-fanhui2 text-lg"></text></view>
			</view>
		</view>

		<!-- 询价单号 -->
		<view class="order-number">
			<text class="number-label">询价单号:</text>
			<text class="number-value">{{inquiryNumber}}</text>
		</view>

		<!-- 订单商品列表 -->
		<view class="order-section">
			<view class="section-title">订单商品列表</view>

			<!-- 商品列表 -->
			<view class="product-list">
				<view class="product-item" v-for="(item, index) in orderData.lists" :key="item.id">
					<!-- 商品基本信息 -->
					<view class="product-basic-info">
						<view class="product-header">
							<text class="product-title">型号：{{ item.products[0].title }}</text>
							<view class="product-price">价格：{{ item.sub_price }}</view>
						</view>

						<view class="product-details">
							<view class="detail-item">
								<text class="detail-label">数量：</text>
								<uv-input type="number" placeholder="请输入数量" border="surround" :value="item.number"
									@change="numberChange($event, index)"></uv-input>
							</view>
						</view>
					</view>

					<!-- 快递信息 - 每个商品独立 -->
					<view class="express-info">
						<view class="info-title">配送信息</view>

						<view class="form-group" @tap="chooseExpress(index)">
							<text class="form-label">快递公司</text>
							<view class="form-value">
								<text v-if="item.express_name" class="value-text">{{ item.express_name_text }}</text>
								<text v-else class="placeholder">请选择</text>
								<text class="wlIcon-fanhui2 margin-left"></text>
							</view>
						</view>

						<view class="form-group">
							<text class="form-label">快递策略</text>
							<view class="form-value">
								<text class="value-text">{{ item.freight_name || '运费到付' }}</text>
							</view>
						</view>

						<!-- <view class="form-group" v-if="item.is_partner == 1" @tap="openFreightPicker(index)">
							<text class="form-label">预估运费</text>
							<view class="form-value">
								<text v-if="item.freight_text" class="value-text">{{ item.freight_text }}</text>
								<text v-else class="placeholder">请选择</text>
								<text class="wlIcon-fanhui2 margin-left"></text>
							</view>
							<uv-picker v-if="item.freight_columns" :ref="`freightPicker${index}`"
								:columns="item.freight_columns" @confirm="freightConfirm($event, index)"
								keyName="name"></uv-picker>
						</view> -->

						<view class="form-group align-start">
							<text class="form-label">订单备注</text>
							<textarea class="remarks-textarea" maxlength="-1" v-model="item.remarks"
								@input="updateRemarks(index, $event)" placeholder="请输入订单备注（可选）"></textarea>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 总金额 -->
		<view class="total-section">
			<view class="total-amount">
				<text class="total-label">总金额:</text>
				<text class="total-value">{{orderData.statis.allsub}}元</text>
			</view>
		</view>

		<!-- 底部操作按钮 -->
		<view class="action-buttons">
			<view class="action-btn cancel" @click="handleCancel">取消</view>
			<view class="action-btn confirm" @click="handleConfirm">提交订单</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				inquiryNumber: '',
				addressData: [],
				orderData: [],
			};
		},
		mounted() {
			uni.$on('selectExpressItem', (data) => {
				this.refreshPage(data.data);
			});
		},
		onLoad(option) {
			if (option.data) {
				const data = JSON.parse(option.data);
				this.inquiryNumber = data.inquiry_number;
				this.products = data.products.map(item => ({
					...item,
					goods_id: item.id
				}));
			}
			this.loadData();
		},
		methods: {
			loadData(address_id) {
				uni.$uv.http.post('/inquiry/getOrderGoodsList', {
					data: this.products,
					address_id: address_id
				}).then(res => {
					if (res.res.code === 1) {
						this.addressData = res.res.data.addressData;
						this.orderData = res.res.data.orderData;

						// 为每个商品初始化快递信息字段
						this.orderData.lists.forEach(item => {
							item.express_name = '';
							item.express_name_text = '';
							item.freight_name = '';
							item.freight_text = '';
							item.freight_columns = [];
							item.remarks = '';
							item.is_partner = 1; // 示例值，实际应根据API返回数据设置
						});
					}
				}).catch(error => {
					console.log('error', error)
					this.$wanlshop.msg('获取失败，请稍后重试', 2000, true)
				});
			},

			numberChange(e, index) {
				const inputValue = parseInt(e.detail || e);
				const maxNumber = this.orderData.lists[index].products[0].number;

				if (isNaN(inputValue) || inputValue <= 0) {
					this.orderData.lists[index].number = 1;
					return;
				} else if (inputValue > parseInt(maxNumber)) {
					this.orderData.lists[index].number = parseInt(maxNumber);
					this.$wanlshop.msg(`数量不能超过${maxNumber}`)
				} else {
					this.orderData.lists[index].number = inputValue;
				}
				// 强制更新视图
				this.$forceUpdate();
			},

			// 获取选中的快递信息
			refreshPage(data) {
				let allList = this.orderData.lists;
				let detail = allList[data.index];
				detail.express_name = data.express_name;
				detail.express_name_text = data.name;
				detail.is_partner = data.is_partner;
				if (detail.is_partner != 1) {
					detail.estimate_price = 0;
				}

				this.orderData.lists[data.index] = detail;

				// 调用接口计算预估运费
				// this.calcFreightPrice(this.orderData, this.addressData, data.index);

				this.$forceUpdate(); // 强制Vue实例重新渲染
			},
			calcFreightPrice(orderInfo, addressData, index) {
				let that = this;
				let item = orderInfo.lists[index];
				if (item.is_partner == 1) {
					// 调用接口
					uni.request({
						url: "/wanlshop/user/getEstimatedExpressFee",
						method: "POST",
						data: {
							addressData: addressData,
							productList: item.products,
							expressName: item.express_name,
						},
						success: function(ret) {
							if (ret.res.code == 1) {
								item.estimate_price = ret.data.fee;
							} else {
								item.estimate_price = '无法预估';
							}
							let freight_text = '';
							let freight_columns = [];
							let service_mode = '';
							if (ret.data.length > 0) {
								freight_text = ret.data[0].name + ' ' + ret.data[0].price + '元';
								freight_columns = [ret.data];
								service_mode = ret.data[0].id;
							}
							that.orderData.lists[index]['freight_text'] = freight_text;
							that.orderData.lists[index]['freight_columns'] = freight_columns;
							that.orderData.lists[index]['service_mode'] = service_mode;
							that.orderData.lists[index] = item;
							that.$forceUpdate(); // 强制Vue实例重新渲染
						}
					})
				}
			},

			// 更新订单备注
			updateRemarks(index, event) {
				this.orderData.lists[index].remarks = event.detail.value;
				// 如果需要强制更新视图
				this.$forceUpdate();
			},
			addAddress(type) {
				this.$wanlshop.to(`/pages/user/address/addressManage?type=${type}`);
			},
			userAddress() {
				this.$wanlshop.to('/pages/user/address/address?source=future');
			},
			// 选择快递 - 传递商品索引
			chooseExpress(index) {
				this.$wanlshop.to('/pages/user/order/express?index=' + index);
			},
			openFreightPicker(index) {
				// 打开运费选择器逻辑
				console.log('打开运费选择器', index);
			},
			freightConfirm(event, index) {
				// 运费确认逻辑
				console.log('运费确认', event, index);
			},
			// 取消操作
			handleCancel() {
				uni.showModal({
					title: '提示',
					content: '确定要取消订单吗？',
					success: (res) => {
						if (res.confirm) {
							uni.navigateBack();
						}
					}
				});
			},

			// 确认生成订单
			handleConfirm() {
				uni.showModal({
					title: '确认订单',
					content: '确定要提交订单吗？',
					success: (res) => {
						if (res.confirm) {
							// 构建符合接口要求的参数格式
							let params = {
								order: {
									address_id: this.addressData.id,
									lists: []
								}
							};

							// 为每个商品添加独立的快递信息
							this.orderData.lists.forEach((shop, index) => {
								const orderItem = {
									express_name: shop.express_name,
									estimate_price: shop.estimate_price,
									service_mode: shop.service_mode,
									remarks: shop.remarks,
									products: []
								};

								// 添加商品信息
								shop.products.forEach(product => {
									orderItem.products.push({
										goods_id: product.id, // 商品ID
										number: parseInt(product.number) // 数量
									});
								});

								params.order.lists.push(orderItem);
							});

							console.log('提交订单参数:', params);

							uni.$uv.http.post('/inquiry/addOrder', {
								order: params.order
							}).then(res => {
								if (res.res.code == 1) {
									this.$wanlshop.msg('您的订单已提交，请耐心等待百润茂核实订单后及时支付！', 3000, true);
									setTimeout(() => {
										uni.redirectTo({
											url: '/pages/future/order/order'
										});
									}, 3000)
								} else {
									this.$wanlshop.msg(res.msg, 3000, true, 'none');
								}
							}).catch(error => {
								console.error('提交订单失败:', error);
								this.$wanlshop.msg('获取失败，请稍后重试', 2000, true)
							});
						}
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 30rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
		box-sizing: border-box;
		padding-bottom: 140rpx;
	}

	.order-number {
		display: flex;
		align-items: center;
		background-color: #fff;
		border-radius: 12rpx;
		padding: 24rpx 30rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

		.number-label {
			font-size: 28rpx;
			color: #666;
			margin-right: 16rpx;
		}

		.number-value {
			font-size: 28rpx;
			color: #333;
			font-weight: bold;
		}
	}

	.order-section {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 24rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.section-title {
		font-size: 30rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 24rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.product-list {
		.product-item {
			padding: 30rpx;
			margin-bottom: 24rpx;
			background: #fafafa;
			border-radius: 12rpx;
			border: 1rpx solid #f0f0f0;

			&:last-child {
				margin-bottom: 0;
			}
		}

		.product-basic-info {
			padding-bottom: 24rpx;
			border-bottom: 1rpx dashed #e8e8e8;
			margin-bottom: 24rpx;
		}

		.product-header {
			display: flex;
			justify-content: space-between;
			align-items: flex-start;
			margin-bottom: 16rpx;

			.product-title {
				font-size: 28rpx;
				color: #333;
				font-weight: 500;
				flex: 1;
				margin-right: 20rpx;
				line-height: 1.4;
			}

			.product-price {
				font-size: 28rpx;
				color: #fe6600;
				font-weight: bold;
			}
		}

		.product-details {
			.detail-item {
				display: flex;
				align-items: center;
				margin-bottom: 8rpx;

				.detail-label {
					font-size: 26rpx;
					color: #666;
				}

				.detail-value {
					font-size: 26rpx;
					color: #333;
					font-weight: 500;
				}
			}
		}

		.express-info {
			.info-title {
				font-size: 28rpx;
				color: #333;
				font-weight: 500;
				margin-bottom: 20rpx;
				padding-bottom: 16rpx;
				border-bottom: 1rpx solid #f0f0f0;
			}

			.form-group {
				display: flex;
				align-items: center;
				padding: 24rpx 0;
				border-bottom: 1rpx solid #f5f5f5;

				&.align-start {
					align-items: flex-start;
				}

				&:last-child {
					border-bottom: none;
				}

				.form-label {
					font-size: 26rpx;
					color: #666;
					width: 160rpx;
					flex-shrink: 0;
				}

				.form-value {
					flex: 1;
					display: flex;
					align-items: center;
					justify-content: flex-end;

					.value-text {
						font-size: 26rpx;
						color: #333;
					}

					.placeholder {
						font-size: 26rpx;
						color: #999;
					}

					.arrow-icon {
						font-size: 24rpx;
						color: #999;
						transform: rotate(-90deg);
						margin-left: 16rpx;
					}
				}

				.remarks-textarea {
					flex: 1;
					min-height: 100rpx;
					font-size: 26rpx;
					padding: 20rpx;
					border: 1rpx solid #e0e0e0;
					border-radius: 8rpx;
					box-sizing: border-box;
					background: #fff;
				}
			}
		}
	}

	.total-section {
		background-color: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

		.total-amount {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.total-label {
				font-size: 30rpx;
				color: #333;
				font-weight: bold;
			}

			.total-value {
				font-size: 36rpx;
				color: #fe6600;
				font-weight: bold;
			}
		}
	}

	.action-buttons {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		padding: 20rpx 30rpx;
		background-color: #fff;
		box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.1);

		.action-btn {
			flex: 1;
			padding: 24rpx;
			text-align: center;
			border-radius: 8rpx;
			font-size: 30rpx;
			font-weight: 500;
			margin: 0 10rpx;

			&.cancel {
				background-color: #fff;
				color: #666;
				border: 1rpx solid #e0e0e0;
			}

			&.confirm {
				background-color: #fe6600;
				color: #fff;
			}
		}
	}
</style>